package org.learn.simple.file.server.parse;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.parser.Tag;
import org.jsoup.select.Elements;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Collection;

/**
 * html解析器
 * @author <a href="mailto:675464934@qq.com">Terrdi</a>
 * @date 2021/12/19
 * @since 1.8
 **/
public class HtmlParser implements AutoCloseable, Cloneable {
    private final Document document;

    public HtmlParser(String path) throws IOException {
        this.document = Jsoup.parse(new File(this.getClass().getClassLoader().getResource(path).getFile()), StandardCharsets.UTF_8.name());
    }

    private HtmlParser(Document document) {
        this.document = document;
    }

    public void add(String fileName) {
        Elements elements = this.document.getElementsByTag("ul");
        Element ul = elements.get(0);
        Element li = new Element("li");
        ul.appendChild(li);
        Element a = new Element("a");
        a.attr("href", fileName);
        a.appendText(fileName);
        li.appendChild(a);
    }

    public void addAll(Collection<String> fileNames) {
        fileNames.forEach(this::add);
    }

    public static void main(String[] args) throws IOException {
        HtmlParser htmlParser = new HtmlParser("template.html");

        System.out.println(htmlParser);
    }

    @Override
    public void close() throws Exception {

    }

    @Override
    protected Object clone() throws CloneNotSupportedException {
        return new HtmlParser(this.document.clone());
    }

    @Override
    public String toString() {
        return document.html();
    }
}
